package com.message.api.user.service.impl;

import com.message.api.user.service.SsoService;
import com.message.api.user.vo.UserContextResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;

import java.util.concurrent.TimeUnit;

@Service
public class SsoServiceImpl implements SsoService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${sso.appId}")
    private String appId;

    @Value("${sso.secret}")
    private String secret;

    private String accessTokenKey = "accessToken";
    private String refreshTokenKey = "refreshToken";

    public String getAccessToken() {
        String accessToken = redisTemplate.opsForValue().get(accessTokenKey);
        if (accessToken != null) {
            return accessToken;
        }
        // 缓存中没有 accessToken，则从远程获取
        String refreshToken = redisTemplate.opsForValue().get(refreshTokenKey);
        if (refreshToken == null) {
            refreshToken = requestRefreshToken(); // 第一次获取 refreshToken
        }
        accessToken = requestAccessToken(refreshToken); // 使用 refreshToken 获取 accessToken
        if (accessToken != null) {
            // 将 accessToken 缓存到 Redis，并设置过期时间
            redisTemplate.opsForValue().set(accessTokenKey, accessToken, 7200, TimeUnit.SECONDS);
        }
        return accessToken;
    }

    public String requestRefreshToken () {
        // 构造请求参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("appId", appId);
        requestBody.put("secret", secret);
        requestBody.put("timestamp", System.currentTimeMillis());
        requestBody.put("scope", "app");

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送 POST 请求获取 refresh_token
        ResponseEntity<Map> response = restTemplate.postForEntity(
                "https://sc.gcu.edu.cn/gateway/oauth2/token/getAccessToken",
                requestEntity,
                Map.class
        );

        // 解析响应结果
        if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
            Map<String, Object> responseBody = response.getBody();
            if (responseBody.containsKey("data")) {
                Map<String, String> data = (Map<String, String>) responseBody.get("data");
                String refreshToken = data.get("refreshToken");
                if (refreshToken != null) {
                    // 将 refresh_token 缓存到 Redis，并设置过期时间
                    redisTemplate.opsForValue().set(refreshTokenKey, refreshToken, 86400, TimeUnit.SECONDS);
                    return refreshToken;
                }
            }
        }
        throw new RuntimeException("Failed to retrieve refresh_token.");
    }

    public String requestAccessToken(String refreshToken) {
        // 构造请求参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("appId", appId);
        requestBody.put("refreshToken", refreshToken);
        requestBody.put("timestamp", System.currentTimeMillis());
        requestBody.put("scope", "app");

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送 POST 请求刷新 accessToken
        ResponseEntity<Map> response = restTemplate.postForEntity(
                "https://sc.gcu.edu.cn/gateway/oauth2/token/refreshToken",
                requestEntity,
                Map.class
        );

        // 解析响应结果
        if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
            Map<String, Object> responseBody = response.getBody();
            if (responseBody.containsKey("data")) {
                Map<String, String> data = (Map<String, String>) responseBody.get("data");
                return data.get("accessToken");
            }
        }
        throw new RuntimeException("Failed to retrieve access_token.");
    }

    public String getUserContext(String ticket) {
        // 构造请求参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("appid", appId);
        requestBody.put("ticket", ticket);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBasicAuth(appId, secret); // 使用基本身份验证添加appId和secret
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送 POST 请求获取用户上下文
        UserContextResponseVo response = restTemplate.postForObject(
                "https://sc.gcu.edu.cn/gateway/ticket/user/acquirecontext?accessToken={accessToken}",
                requestEntity,
                UserContextResponseVo.class,
                getAccessToken()
        );

        // 返回用户上下文
        return response.getData().getJobNo();
    }




}


//@Service
//public class SsoServiceImpl implements SsoService {
//    @Value("${sso.appId}")
//    private String appId;
//
//    @Value("${sso.secret}")
//    private String secret;
//
////    private String accessToken;
//
//    @Autowired
//    private RestTemplate restTemplate;
//
//    public AccessTokenResponseVo getAccessToken() {
//        // 构造请求参数
//        Map<String, Object> requestBody = new HashMap<>();
//        requestBody.put("appId", appId);
//        requestBody.put("secret", secret);
//        requestBody.put("timestamp", System.currentTimeMillis());
//        requestBody.put("scope", "app");
//
//        // 设置请求头
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
//        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
//
//        // 发送 POST 请求获取 accessToken
//        AccessTokenResponseVo response = restTemplate.postForObject(
//                "https://sc.gcu.edu.cn/gateway/oauth2/token/getAccessToken",
//                requestEntity,
//                AccessTokenResponseVo.class
//        );
////        // 更新 accessToken
////        if (response != null) {
////            accessToken = response.getData().getAccessToken();
////        }
//        return response;
//    }
//
//    public String getUserContext(String ticket) {
//        // 构造请求参数
//        Map<String, Object> requestBody = new HashMap<>();
//        requestBody.put("appid", appId);
//        requestBody.put("ticket", ticket);
//
//        // 设置请求头
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
//        headers.setBasicAuth(appId, secret); // 使用基本身份验证添加appId和secret
//        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
//
//        // 发送 POST 请求获取用户上下文
//        UserContextResponseVo response = restTemplate.postForObject(
//                "https://sc.gcu.edu.cn/gateway/ticket/user/acquirecontext?accessToken={accessToken}",
//                requestEntity,
//                UserContextResponseVo.class,
//                getAccessToken()
//        );
//
//        // 返回用户上下文
//        return response.getData().getJobNo();
//    }
//
//    public String refreshAccessToken(String refreshToken) {
//        // 构造请求参数
//        Map<String, Object> requestBody = new HashMap<>();
//        requestBody.put("appId", appId);
//        requestBody.put("refreshToken", refreshToken);
//        requestBody.put("timestamp", System.currentTimeMillis());
//        requestBody.put("scope", "app");
//
//        // 设置请求头
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
//        headers.setBasicAuth(appId, secret); // 使用基本身份验证添加appId和secret
//        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
//
//        // 发送 POST 请求刷新 AccessToken
//        String accessToken = restTemplate.postForObject(
//                "https://sc.gcu.edu.cn/gateway/oauth2/token/refreshToken",
//                requestEntity,
//                String.class
//        );
//
//        // 返回刷新后的 AccessToken
//        return accessToken;
//    }
//
//    public String getToken() {
//        AccessTokenResponseVo accessTokenVo = getAccessToken();
//        int expireIn = accessTokenVo.getData().getExpireIn();
//
//        //提取有效时间，小于十分钟则刷新token
//        if(expireIn <= 600){
//
//            return refreshAccessToken(accessTokenVo.getData().getRefreshToken());
//
//        }else return accessTokenVo.getData().getAccessToken();
//
//    }
//
//
//}

